//Mark O Meara
//08332240
//CS2014 - Assignment2
//Due: 31/03/10

import org.jdom.Attribute;
import org.jdom.Element;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

public class ElementMethods {
	
	//Converts Element names to uppercase
	public static void childrenToUpper(Element e){
		List<?> childlst = e.getChildren();
		Iterator<?> childiterator = childlst.iterator();
		//While there is a child
		while(childiterator.hasNext()){
			childrenToUpper((Element) childiterator.next());
		}
		//Set element name to uppercase
		e.setName(e.getName().toUpperCase());
	}
	
	//Method to convert year attribute to element
	public static void yearAttributeToElement(Element e){
		//Get all elements with name 'book'
		List<?> booklst = e.getChildren("BOOK");
		Iterator<?> bookiterator = booklst.iterator();
		//While there is another book element
		while(bookiterator.hasNext()){
			//b = book element
			Element b = (Element) bookiterator.next();
			//a = year attribute
			Attribute a = b.getAttribute("year");
			//y = new element called year
			Element y = new Element("year");
			//Assigning value for the new year element
			y.addContent(a.getValue());
			//Add new element to child
			b.addContent(y);
			//Remove year attribute
			b.removeAttribute("year");
		}
	}
	
	public static void addEuroPrice(Element e){
		List<?> booklst = e.getChildren("BOOK");
		Iterator<?> bookiterator = booklst.iterator();
		while(bookiterator.hasNext()){
			Element book = (Element) bookiterator.next();
			Element p = book.getChild("PRICE");
			Element dollar = new Element("Dollar");
			dollar.addContent(p.getValue());
			//Calculate Euro price
			double eurovalue = (Double.parseDouble(p.getValue())) * 0.642178269;
			//Round to two decimal places
			eurovalue = toTwoDecimalPlaces(eurovalue);
			//Create Euro element
			Element euro = new Element("Euro");
			//Add euro price as the element content
			euro.addContent(Double.toString(eurovalue));
			//Remove content of price element
			p.removeContent();
			//Add new price element
			p.addContent(dollar);
			p.addContent(euro);
		}
	}
	
	//Used to convert Euro values to two decimal places
	private static Double toTwoDecimalPlaces(Double d){
    	DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d));
	}
	
}